package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.enums.ResultCode;
import com.bosssoft.boss_exam_core.exception.DeleteEntityException;
import com.bosssoft.boss_exam_core.exception.QueryDataException;
import com.bosssoft.boss_exam_core.exception.ReflectionException;
import com.bosssoft.boss_exam_core.exception.UpdateEntityException;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.MyGroup;
import com.bosssoft.boss_exam_db.service.busines.GroupService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.bosssoft.boss_exam_web.common.annotation.LoginApplicant;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController

@Validated
@Slf4j
@Api(value="集团控制器")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @ApiOperation(value="集团查询", notes="可根据集团名称查询集团" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="groupname", value="集团名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })
    @GetMapping("/admin/group/list")
    public Object list(@LoginAdmin String adminId,
                       @RequestParam String groupname,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if ( adminId == null) {
            return ResponseUtil.unlogin();
        }
        PageInfo<MyGroup> groupPageInfo = groupService.queryByCondition(groupname,page, limit, sort, order);
        if(groupPageInfo==null){
            log.error("【业余错误】，查询pageInfo为空");
            throw new QueryDataException();
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", groupPageInfo.getTotal());
            data.put("items", groupPageInfo.getList());
            return ResponseUtil.ok(data);
        }
    }

    @ApiOperation(value="集团添加", notes="添加集团" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="group", value="集团对象json", dataType = "MyGroup", required=true, dataTypeClass= MyGroup.class),
    })
    @PostMapping("/admin/group/create")
    public Object create(@LoginAdmin String adminId, @RequestBody MyGroup group) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = groupService.saveNotNull(group);
        if(recordNum==1){
            return ResponseUtil.ok(group);
        }else{
            log.error("【系统错误】 保存集团失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="集团详细信息查询", notes="可根据集团的ID查询详情" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="集团ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/admin/group/read")
    public Object read(@LoginAdmin String  adminId, @NotNull Integer id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        MyGroup group = null;
        try {
            group = groupService.selectByKey(id);
        }  catch (NoSuchMethodException | InvocationTargetException |IllegalAccessException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e){
            log.error("【业务错误】 读取实体异常"+e);
            throw  new QueryDataException();
        }
        return ResponseUtil.ok(group);
    }


    @ApiOperation(value="集团更新", notes="更新集团" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="group", value="集团对象json，必须携带集团ID", dataType = "MyGroup", required=true, dataTypeClass= MyGroup.class),
    })
    @PostMapping("/admin/group/update")
    public Object update(@LoginAdmin String  adminId, @RequestBody MyGroup group) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = groupService.updateNotNull(group);
        if(recordNum==1){
            return ResponseUtil.ok(group);
        }else{
            log.error("【系统错误】 保存集团失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="集团删除", notes="可根据集团的ID逻辑删除集团" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="集团ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @PostMapping("/admin/group/delete")
    public Object delete(@LoginAdmin String adminId, @RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        MyGroup group = new MyGroup();
        group.setId(id);
        try {
            int recordNum = groupService.deleteCascade(group);
            if(recordNum==1){
                return ResponseUtil.ok();
            }else {
                log.info("【系统错误】 逻辑集团失败");
                throw  new DeleteEntityException();
            }
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }
    }

    @ApiOperation(value="查询集团", notes="查询所有集团" ,httpMethod="GET",response = Object.class)
    @GetMapping("/pc/group/queryGroups")
    public Object getAllGroup(@LoginApplicant String applicantId){
        if (applicantId == null) {
            return ResponseUtil.unlogin();
        }
        List<MyGroup> groups =  groupService.queryAllGroup();
        return ResponseUtil.ok(groups);
    }
}
